<template>
  <div class="user-tab-connection">
    <!-- connected accounts -->
    <v-card class="mb-7">
      <v-card-title>
        <span class="text-black">{{ t('message.profile.connect.title') }}</span>
      </v-card-title>
      <v-card-subtitle>
        <span class="text-[#000000DE]">{{ t('message.profile.connect.subtitle') }}</span>
      </v-card-subtitle>

      <v-card-text class="pb-2">
        <v-list
          dense
          class="py-0 bg-white"
        >
          <v-list-item
            v-for="(account, index) in connectedAccounts"
            :key="index"
            :class="`px-0 ${index > 0 ?'mt-6':'mt-3'}`"
          >
            <div class="flex flex-row">
              <discord class="me-3" v-if="account.title === 'Discord'"></discord>
              <telegram class="me-3" v-if="account.title === 'Telegram'"></telegram>

              <div class="d-flex align-center flex-grow-1 flex-wrap">
                <div class="me-2">
                  <v-list-item-title class="text-sm">
                    {{ account.title }}
                  </v-list-item-title>
                  <v-list-item-subtitle v-if="account.connected">
                    <a
                      :href="account.link"
                      target="_blank"
                      rel="nofollow"
                      class="text-decoration-none text-truncate text-[#9155fd]"
                    >
                      {{ account.username }}
                    </a>
                  </v-list-item-subtitle>
                  <v-list-item-subtitle v-else>
                    {{ t('message.profile.connect.notConnect') }}
                  </v-list-item-subtitle>
                </div>

                <v-spacer></v-spacer>

                <v-btn
                  color="#8a8d93"
                  variant="outlined"
                  min-width="38"
                  class="px-0"
                  @click.stop="bindDC"
                  v-if="index === 0"
                >
                  <v-icon size="20" color="#8a8d93">
                    {{ account.connected ? 'mdi-close' : 'mdi-link-variant' }}
                  </v-icon>
                </v-btn>
                <v-btn
                  color="#8a8d93"
                  variant="outlined"
                  min-width="38"
                  class="px-0"
                  @click.stop="bindTG"
                  v-else
                >
                  <v-icon size="20" color="#8a8d93">
                    {{ account.connected ? 'mdi-close' : 'mdi-link-variant' }}
                  </v-icon>
                </v-btn>
              </div>
            </div>
          </v-list-item>
        </v-list>
      </v-card-text>
    </v-card>

    <!-- social accounts -->
    <v-card>
      <v-card-title>
        <span class="text-black">{{ t('message.profile.connect.social.title') }}</span>
      </v-card-title>
      <v-card-subtitle>
        <span class="text-[#000000DE]">{{ t('message.profile.connect.social.subtitle') }}</span>
      </v-card-subtitle>
      <v-card-text>
        <v-list
          dense
          class="py-0 bg-white"
        >
          <v-list-item
            v-for="(account,index) in socialAccounts"
            :key="account.title"
            :class="`px-0 ${index > 0 ?'mt-6':'mt-3'}`"
          >
            <div class="flex flex-row">
              <twitter class="me-3" v-if="account.title === 'Twitter'"></twitter>
              <youtube class="me-3" v-if="account.title === 'Youtube'"></youtube>
              <tiktok class="me-3" v-if="account.title === 'Tiktok'"></tiktok>
              <facebook class="me-3" v-if="account.title === 'Facebook'"></facebook>
              <whatsapp class="me-3" v-if="account.title === 'WhatsApp'"></whatsapp>
              <talk class="me-3" v-if="account.title === 'Kakaotalk'"></talk>
              <img class="me-3" :src="line" v-if="account.title === 'Line'"/>
              <img class="me-3" :src="instagram" v-if="account.title === 'Instagram'"/>

              <div>
                <v-list-item-title class="text-sm">
                  {{ account.title }}
                </v-list-item-title>
                <v-list-item-subtitle v-if="account.connected">
                  <a
                    :href="account.link"
                    target="_blank"
                    rel="nofollow"
                    class="text-decoration-none text-truncate text-[#9155fd]"
                  >
                    {{ account.username }}
                  </a>
                </v-list-item-subtitle>
                <v-list-item-subtitle v-else>
                  Not connected
                </v-list-item-subtitle>
              </div>

              <v-spacer></v-spacer>

              <v-btn
                color="#8a8d93"
                variant="outlined"
                min-width="38"
                class="px-0"
              >
                <v-icon size="20" color="#8a8d93">
                  {{ account.connected ? 'mdi-close' : 'mdi-link-variant' }}
                </v-icon>
              </v-btn>
            </div>
          </v-list-item>
        </v-list>
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup lang="ts">
import twitter from '@/icons/social/twitter.svg?component'
import youtube from '@/icons/social/youtube.svg?component'
import tiktok from '@/icons/social/tiktok.svg?component'
import talk from '@/icons/social/talk.svg?component'
import whatsapp from '@/icons/social/whatsapp.svg?component'
import facebook from '@/icons/social/facebook.svg?component'
import discord from '@/icons/social/discord.svg?component'
import telegram from '@/icons/social/telegram.svg?component'
import instagram from '@/assets/images/instagram.png'
import line from '@/assets/images/line.png'
import {bindSocialAccountApi} from "@/api/system/user";
import Dialog from "@/components/dialog/dialog";

import UserStore from "@/store/UserStore"
import {onMounted, onUnmounted, ref, watchEffect} from "vue"

import axios from "axios"
import {useI18n} from "vue-i18n";

var oauthWin: any = null
var previousUrl = null
const {t} = useI18n()

interface connectedAccount {
  title: string,
  connected: boolean,
  username?: string,
  link?: string
}

const connectedAccounts = ref<connectedAccount[]>([
  {
    title: 'Discord',
    connected: false,
    username: ''
  },
  {
    title: 'Telegram',
    connected: false,
    username: ''
  }
])

const socialAccounts = ref<connectedAccount[]>([
  {
    title: 'Twitter',
    // link: 'https://twitter.com/theme_selection',
    // username: '@Theme_Selection',
    connected: false,
  },
  {
    title: 'Youtube',
    connected: false,
  },
  {
    title: 'Tiktok',
    connected: false,
  },
  {
    title: 'Facebook',
    connected: false,
  },
  {
    title: 'Instagram',
    connected: false,
  },
  {
    title: 'WhatsApp',
    connected: false,
  },
  {
    title: 'Line',
    connected: false,
  },
  {
    title: 'Kakaotalk',
    connected: false,
  },
])

const userStore = UserStore()

const bindTG = () => {
  console.log('enter bind tg')
  // @ts-ignore
  window.Telegram.Login.auth({bot_id: '5547505264', request_access: 'write', embed: 1}, (data) => {
    console.log('telegram res:', data);
    bindSocialAccountApi({
      accountId: data.id,
      accountName: data.username,
      type: 2
    }).then((res: any) => {
      console.log('bindSocialApi res:', res)
      connectedAccounts.value[1].username = 'ID: ' + res
      Dialog('bind successfully')

      connectedAccounts.value[1].connected = true
      const userInfo = {
        ...userStore.userInfo,
        tgId: res
      }
      userStore.setUserInfo(userInfo)
    }).catch((err: any) => {
      console.log('bind social err:', err)
    })
  });
}

const discordAuthorize = async (code: string) => {
  if (code === '') {
    Dialog(t('message.system.bind.dcCode'))
    return
  }
  try {
    const tokenResponse = await axios.postForm('https://discord.com/api/oauth2/token', {
        'client_id': '999165256309944330',
        'client_secret': 'vTxV9wUDZN82RoCQTkMD6QDgiKnhiN0x',
        'grant_type': 'authorization_code',
        'redirect_uri': 'https://sdao.win/profile',
        'scope': 'identify',
        'code': code + ''
      },
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      }
    )
    console.log('token:', tokenResponse.data.access_token)
    if (tokenResponse.data.access_token) {
      axios.get("https://discord.com/api/users/@me", make_config(tokenResponse.data.access_token)).then(response => {
        console.log('discord user resp:', response.data)
        console.log('username:', response.data.username)
        const username = response.data.username + '#' + response.data.discriminator
        const id = response.data.id
        bindSocialAccountApi({
          accountId: id,
          accountName: username,
          type: 1
        }).then((res: any) => {
          console.log('bindSocialApi res:', res)
          connectedAccounts.value[0].username = 'ID: ' + res
          console.log('username:', connectedAccounts.value[0].username)
          Dialog(t('message.system.bind.success'))

          connectedAccounts.value[0].connected = true
          const userInfo = {
            ...userStore.userInfo,
            dcId: res
          }
          userStore.setUserInfo(userInfo)
        }).catch((err: any) => {
          console.log('bind social err:', err)
        })
      }).catch(err => {
        console.log(err)
      });
    } else {
      Dialog(t('message.system.bind.fail'))
    }
  } catch
    (e) {
    console.log('err:', e)
  }
}

const receiveMessage = event => {
  console.log(event)
  if (event.origin !== import.meta.env.VITE_DOMAIN) {
    return
  }
  const {data} = event
  console.log('data:', data)
  if (typeof data === "string" && data.includes('code=')) {
    discordAuthorize(data.substring(6))
    oauthWin.close()
  }
}

const bindDC = () => {
  window.removeEventListener('message', receiveMessage)
  console.log('enter bind dc')
  const url = 'https://discord.com/api/oauth2/authorize?client_id=999165256309944330&redirect_uri=https%3A%2F%2Fsdao.win%2Fprofile&response_type=code&scope=identify'
  // window.location.replace(url)

  var newWinHeight = 600
  var newWinWidth = 600
  var winWidth = window.screen.availWidth;  //获取屏幕宽度
  var winHeight = window.screen.availHeight;  //获取屏幕高度
  var left = (winWidth - newWinWidth) / 2; //获取新窗口距离屏幕左侧的位置
  var top = (winHeight - newWinHeight) / 2; //获取新窗口距离屏幕顶部的位置
  const strWindowFeatures = 'width=' + newWinWidth + ',height=' + newWinHeight + ',left=' + left + ',top=' + top + ',toolbar=no,menubar=no,modal=false,alwaysRaised=yes,location=no,status=no'
  if (oauthWin === null || (oauthWin !== null && oauthWin.closed)) {
    oauthWin = window.open(url, 'newwindow', strWindowFeatures)
    oauthWin.focus()
  } else if (previousUrl !== url) {
    oauthWin = window.open(url, 'newwindow', strWindowFeatures)
    oauthWin.focus()
  } else {
    oauthWin.focus()
  }

  // name:弹出窗口的名字,可不填，用''代替
  // toolbar=no 是否显示工具栏。yes为显示
  // menubar=no 是否显示菜单栏。yes为显示
  // location=no 是否显示地址字段。yes为显示
  // status=no 是否添加状态栏。yes为可以
  // 设置ref属性，优化seo，告诉搜索引擎不对新页面进行爬取
  oauthWin.ref = 'nofollow'

}

/* Make a function to give us configuration for the Discord API */
function make_config(authorization_token) { // Define the function
  return { // Define "data"
    headers: { // Define "headers" of "data"
      "authorization": `Bearer ${authorization_token}` // Define the authorization
    }
  }; // Return the created object
}

const init = async () => {
  // @ts-ignore
  const tgId = userStore.userInfo?.tgId
  console.log('tgId:', tgId)
  if (tgId !== null) {
    connectedAccounts.value[1].username = tgId ? 'ID: ' + tgId : 'ID: '
    connectedAccounts.value[1].connected = true
  }
  // @ts-ignore
  const dcId = userStore.userInfo?.dcId
  console.log('dcId:', dcId)
  if (dcId !== null) {
    connectedAccounts.value[0].username = dcId ? 'ID: ' + dcId : 'ID: '
    connectedAccounts.value[0].connected = true
  }
}

init()

watchEffect(() => {
  const params = window.location.search
  if (window.opener) {
    window.opener.postMessage(params)
    window.close()
  }
})

onMounted(() => {
  window.addEventListener("message", event => receiveMessage(event), false)
})

onUnmounted(() => {
  window.removeEventListener("message", event => receiveMessage(event), false)
})

</script>
